<template>
  <div class="roles">
    <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="roleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row v-for="(item1,index1) in scope.row.children" :key="item1.id"  :class="['bdbottom',index1 === 0 ? 'bdtop':'','venter']">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag  closable
                    @close="removeRightById(scope.row, item1.id)">
                  {{item1.authName}}
                </el-tag>
                 <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 二级 -->
                <el-row v-for="(item2, index2) in item1.children" :key="item2.id" :class="[index2 !== 0 ? 'bdtop' : '','venter']">
                  <el-col :span="6">
                    <el-tag type="success"  closable
                    @close="removeRightById(scope.row, item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3, index3) in item2.children" :key="item3.id" closable
                    @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre> -->
            
          </template>  
        </el-table-column> 
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column> 
        <el-table-column prop="roleName" label="角色列表"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column> 
        <el-table-column label="操作" width="300">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"  @click="editRoleClick(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRightDialog(scope.row)">分配权限</el-button>
          </template>  
        </el-table-column> 

      </el-table>
    </el-card>
        <!-- 弹出对话框区域 -->
    <el-dialog
      title="添加角色"
      :visible.sync="roleDialogVisible"
      width="30%"
      @close="roleDialogClose()">
      <!-- 主体 -->
      <el-form :model="roleForm" label-width="80px" ref="roleFormRef">
        <el-form-item label="角色名称" prop="usersname">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <template #footer>
        <span class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleUser()">确 定</el-button>
      </span>
      </template>
   </el-dialog>
      <!-- 弹出修改按钮区域 -->
      <el-dialog
      title="修改角色"
      :visible.sync="editRoleDialogVisible"
      width="30%"
      @close="editRoleDialogClose()">
      <!-- 主体 -->
      <el-form :model="editRoleForm" label-width="80px" ref="editRoleFormRef">
        <el-form-item label="角色名称" prop="usersname">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <template #footer>
        <span class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleUser()">确 定</el-button>
      </span>
      </template>
   </el-dialog>
   <!-- 分配权限对话框 -->
   <el-dialog
    title="分配权限"
    :visible.sync="setRightDialogVisible"
    width="50%"
    @close="setRightDialogClosed()">
     <el-tree :data="rightsLists" :props="treeProps" show-checkbox 
     node-key="id" default-expand-all :default-checked-keys="defkeys" ref="treeRef"></el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </template>
   </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 添加的用户信息
      roleForm: {
        roleName: '',
        roleDesc: ''
      },

      roleDialogVisible: false,
      // 规则
      // roleFormRule: {
      //   usersname: [
      //     { required: true, message: '请输入角色名称', trigger: 'blur' },
      //     { min: 3, max: 9, message: '长度在 3 到 9 个字符', trigger: 'blur' }
      //   ]
      // }
      editRoleDialogVisible: false,
       editRoleForm: {},
      //  分配权限框
      setRightDialogVisible: false,
      // 所有权限列表
      rightsLists: [],
      // 树形控件的绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中
      defkeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
       }
    
  },
  created() {
    // 获取角色列表
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data:res } = await this.$http.get('roles')
      if(res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！');
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 关闭弹出框显示
    roleDialogClose() {
      this.$refs.roleFormRef.resetFields()
    },
        // 添加用户点击按扭确定
    roleUser() {
      this.$refs.roleFormRef.validate(async valid => {
        
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data:res } = await this.$http.post('roles', this.roleForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败!')
        }else {
          this.$message.success('添加用户成功!')
        }
        
        // 关闭弹出框
        this.roleDialogVisible = false
        // 获取用户列表
        this.getRolesList()
      })
    },
    // 点击修改按钮
    async editRoleClick(id) {
       const { data:res } = await this.$http.get('roles/' + id)
       if (res.meta.status !== 200) {
          return this.$message.error('查询用户信息失败！')
       }
       this.editRoleForm = res.data
      //  console.log(this.editRoleForm)
       this.editRoleDialogVisible = true
     },
     editRoleDialogClose() {
        this.$refs.editRoleFormRef.resetFields()
     },
    //  修改表单确定按钮
    editRoleUser() {
       this.$refs.editRoleFormRef.validate(async valid => {
        if(!valid) return
        // 数据请求
        const { data:res } = await this.$http.put('roles/' + this.editRoleForm.id,{
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        })
        if(res.meta.status !== 200) {
          return this.$message.error('更新用户数据失败！')
        }
         //  关闭对话框
        this.editRoleDialogVisible = false

        // 刷新数据列表
        this.getRolesList()
        // 提示修改成功
        this.$message.success('更新用户数据成功')
       })
    },
    // 点击删除按钮
    async removeRoleById(id) {
       const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示', 
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
       
      ).catch(err => err)

       if(confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
       const {data:res} = await this.$http.delete('roles/' + id)
       if(res.meta.status !== 200) {
         return this.$message.error('删除用户失败！')
       }
       this.$message.success('删除用户成功！')
       this.getRolesList()
    },
    // 点击删除权限按钮
    async removeRightById(role, rightId) {
       const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示', 
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
       
      ).catch(err => err)
       
        if(confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const  {data:res} = await this.$http.delete(`roles/${role.id}/rights/${ rightId}`)
      if(res.meta.status !== 200) {
        return this.$message.error('获取用户权限失败！')
      }
      // 更新
      role.children = res.data
    },
    // 点击分配权限
    async setRightDialog(role) {
      this.roleId = role.id

      const { data:res } = await this.$http.get('rights/tree')
      
      if(res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      
      this.rightsLists = res.data
      // console.log(this.rightsLists)
      // 获取三级节点的id
      this.getLeafKeys(role, this.defkeys)
      this.setRightDialogVisible = true
    },
    // 通过递归，获取三级id，并保存到defkeys中
    getLeafKeys(node, arr) {
      // 如果node不包含children属性，就是三级
      if(!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      });
    },
    // 分配权限对话框关闭事件
    setRightDialogClosed() {
      this.defkeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.
        getCheckedKeys(),
        ...this.$refs.treeRef.
        getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

      const {data:res} = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if(res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
 }
}
</script>

<style>
  .el-card {
    margin-top: 15px;
  }
  .el-table {
    margin-top: 15px;
  }
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .venter {
    display: flex;
    align-items: center;
  }
</style>